package com.example.todolist.common;


import com.example.todolist.util.HttpServletRequestUtil;
import com.example.todolist.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Email: m15602498163@163.com
 * @Author: yoonada
 * @Date: 2020/9/12
 * @Time: 12:46 下午
 * @Msg:
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthAspect {

    private final JwtUtil jwtUtil;

    @Around("@annotation(com.example.todolist.common.CheckLogin)")
    public Object checkLogin(ProceedingJoinPoint point) {
        try {
            log.info("point:{}",point);
            checkToken();
            return point.proceed();
        } catch (Throwable throwable) {
            log.error("报错如下:{}",throwable.getMessage(),throwable);
            throw new SecurityException("AuthAspect.checkLogin抛出异常了");
        }
    }

    private void checkToken() {
        // 1、从header里面获取token
        HttpServletRequest request = HttpServletRequestUtil.getHttpServletRequest();
        String token = request.getHeader("token");
        // 2、校验token是否合法
        Boolean isValid = jwtUtil.validateToken(token);
        if (!isValid) {
            throw new SecurityException("token异常");
        }
//        3、如果校验成功，将用户的信息设置到request的attribute里面
        Claims claims = jwtUtil.getClaimsFromToken(token);
        request.setAttribute("uid", claims.get("uid"));
        request.setAttribute("nick_name",claims.get("nick_name"));
    }




}
